/**
 * 公司信息组件
 */
layui.define(['layer', 'form','upload','uploadList','staticData','autocomplete'], function (exports) {
    var $ = layui.jquery, layer = layui.layer, form = layui.form ,
        com = layui.com,
        setter = layui.setter,
        upload = layui.upload,
        uploadList = layui.uploadList,
        autocomplete = layui.autocomplete,
        staticData = layui.staticData,
        request = layui.request,$province,$city,$area,
        fn = {
            layer_index: 0,
            callBack : null
            ,async getCompanyData(){
                let company = {};
                await request.get('/scm/company/info').then(res=>{
                    company = res.data;
                }).catch(()=>{
                    layer.close(fn.layer_index);
                });
                return company;
            }
            // 加载文件
            ,renderFileList(othis){
                let isEdit = (othis.attr('edit')||'false')=='true';
                request.postForm('/scm/file/fileList',{
                    docId:othis.attr('file-id'),docType:othis.attr('file-type'),businessType:othis.attr('business-type') || ''
                }).then(res => {
                    let ulbox = [];
                    (res.data || []).forEach((item,idx) =>{
                        ulbox.push('<li><a href="/scm/download/file/',item.id,'" target="_blank">',(idx+1),'. ',item.name,'</a>',(isEdit)?'<i class="iconfont iconhuishou remove-file" title="删除" file-id="'+item.id+'"></i>':'','</li>');
                    });
                    // if(ulbox.length>0){
                    //     $('#cus-business-tooltip').hide();
                    // }
                    if(isEdit){
                        if(ulbox.length>0){
                            $('#form-companyinfo-base-manage').find('.upload-title').hide();
                            $('#form-companyinfo-base-manage').find('.file-box').css({'margin-top':'0px'});
                        }else{
                            $('#form-companyinfo-base-manage').find('.upload-title').show();
                            $('#form-companyinfo-base-manage').find('.file-box').css({'margin-top':'25px'});
                        }
                    }
                    othis.find('.file-box').html(ulbox.join(''));
                    if(isEdit){
                        othis.find('.remove-file').click(function () {
                            fn.removeFile($(this),othis);
                        });
                    }
                });
            }
            // 删除文件
            ,removeFile(othis,filebox){
                let fileId = othis.attr('file-id');
                layer.confirm('当前操作不可回退是否继续？',{icon: 3},function (index) {
                    layer.close(index);
                    request.postForm('/scm/file/removes',{ids:fileId}).then(res=>{
                        fn.renderFileList(filebox);
                    });
                });
            }
            // 初始化文件上传
            ,initFile(element) {
                if(!element){
                    element = $('body');
                }
                var $files = element.find('.upload-box');
                $files.each(function (i, o) {
                    let othis = $(o), fileId = othis.attr('file-id'),
                        fileType = othis.attr('file-type'),
                        businessType = othis.attr('business-type') || '',
                        fileMemo = othis.attr('file-memo') || '',
                        btnName = othis.attr('btn-name') || '点击上传',
                        isEdit = (othis.attr('edit')||'false')=='true';
                    othis.html([isEdit?'<div class="upload-title"><span class="upload-text">'+fileMemo+'仅支持图片类型格式上传</span><div class="upload-loading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i></div><a href="javascript:" class="upload-btn"><i class="iconfont iconic_upload"></i>'+btnName+'</a></div>':'','<ul class="file-box scrollbar" ',isEdit?'':'style="margin-top:0"','></ul>'].join(''));
                    fn.renderFileList(othis);
                    if(isEdit){
                        let $loading = othis.find('.upload-loading'),$upload = othis.find('.upload-btn');
                        upload.render({
                            elem:$upload ,url:'/scm/file/upload',size:10240,exts:'pdf|xls|xlsx|doc|docx|ppt|pptx|txt|zip|rar|7z|jpg|jpeg|gif|png|bmp|tif'
                            ,multiple:true,data:{docId:fileId,docType:fileType,businessType:businessType,memo:fileMemo}
                            ,accept:'images',acceptMime:'image/*'
                            ,before:function (res) {
                                $loading.show();
                                $upload.hide();
                            }
                            ,done: function(res){
                                $loading.hide();
                                $upload.show();
                                if(com.isSuccess(res)){
                                    fn.renderFileList(othis);
                                    fn.businessLicenseOcr(res.data.id);
                                }
                            },error:function () {
                                $loading.hide();
                                $upload.show();
                            }
                        });
                    }
                });
            }
            // 识别
            ,businessLicenseOcr(fileId){
                // com.showLoading();
                // request.get('/scm/company/businessLicenseOcr/'.concat(fileId)).then(res =>{
                //     let data = res.data;
                //     if(data && data.name){
                //         let infoh = [
                //             '<div class="layui-row">公司全称：',data.name,'</div>',
                //             '<div class="layui-row">信用代码：',data.socialNo,'</div>',
                //             '<div class="layui-row">公司法人：',data.legalPerson,'</div>',
                //             '<div class="layui-row">公司地址：',data.address,'</div>'
                //         ];
                //         layer.confirm(infoh.join(''),{icon: 3,title:'识别到以下内容是否引用?'},function (index) {
                //             layer.close(index);
                //             form.val('form-companyinfo-base-manage',data);
                //         });
                //     }else{
                //         layer.msg('未能识别到您的营业执照信息');
                //     }
                // });
            }
            // 检查客户名称是否存在
            ,oldCompanyName:''
            ,checkCompanyName(){
                let companyName = $('#companyinfo-base-name').val();
                if(com.isEmpty(companyName) || companyName == fn.oldCompanyName){return;}
                fn.oldCompanyName = companyName;
                request.postForm('/scm/company/checkCompanyName',{'name':companyName}).then(res =>{
                    if(res.data.state==1){
                        // 1：已占用可绑定
                        com.confirm_inquiry('我司销售人员已为您备案公司信息，您可以直接点击确定认领。',function (){
                            fn.claimCompany(res.data.ncustomerId);
                        });
                    }else if(res.data.state==2){
                        // 2：已占用不可绑定
                        com.alertWarn('当前公司名称已被注册，您可以联系销售人员为您找回账户。')
                    }
                });
            }
            // 认领公司信息
            ,claimCompany(ncustomerId){
                request.postForm('/scm/company/claimCompany',{'ncustomerId':ncustomerId}).then(res =>{
                    layer.close(fn.layer_index);
                    layer.msg('认领成功');
                    if(fn.callBack){
                        eval(fn.callBack).call(this,{'id':ncustomerId});
                    }
                });
            }
            // 修改公司信息
            ,async editCompany(callBack){
                fn.callBack = callBack;
                await $.get('/views/sub/company-base-manage.html',{'v':setter.version},function (html) {
                    fn.layer_index = layer.open({
                        title: '公司信息维护'
                        , id: 'win-edit-company'
                        , type: 1
                        , resize: false
                        , shadeClose: true
                        , area: ['720px', 'auto']
                        , content: html
                    });
                });
                let companyData = await fn.getCompanyData();
                form.val('form-companyinfo-base-manage',companyData);
                let $formCompanyinfo = $('#form-companyinfo-base-manage');
                $formCompanyinfo.find('.upload-box').attr({'file-id': companyData.id, 'edit':(companyData.statusId=='audited')?'false':'true'});
                fn.initFile($formCompanyinfo);
                $('#company-base-manage-status-name').addClass(companyData.statusId);
                // 允许修改获取光标
                if(companyData.statusId!='audited'){
                    // $('#cus-business-tooltip').show();
                    let $companyName = $('#companyinfo-base-name');
                    $companyName.focus();
                    autocomplete.render({
                        elem: $companyName,
                        url: '/scm/company/vagueSimpleBusinessQuery',
                        template_txt: '{{d.name}} {{d.creditCode}} {{d.operName}}',
                        template_val: '{{d.name}}',
                        ajaxParams: {
                            type: 'get'
                        },
                        request: {
                            keywords: 'name'
                        },
                        onselect:function (data) {
                           form.val('form-companyinfo-base-manage',{
                               'name':data.name,
                               'socialNo':data.creditCode,
                               'address':data.address,
                               'legalPerson':data.operName
                           });
                            // 检查客户名称是否存在
                            fn.oldCompanyName = '';
                            fn.checkCompanyName();
                        }
                    });
                    // 检查客户名称是否存在
                    $companyName.blur(function (){
                        fn.checkCompanyName();
                    });
                }else{
                    $formCompanyinfo.find('.company-disabled-input').attr({'disabled':true,'lay-verify':null});
                    $formCompanyinfo.find('.company-disabled-input').parent().addClass('form-disabled');
                }
                if(companyData.statusId == 'waitPerfect' && com.isNotEmpty(companyData.auditOpinion) && com.isNotEmpty(companyData.name)){
                    $('#companyinfo-base-manage-tips').show().find('p').html(companyData.auditOpinion);
                }
                // 保存
                form.on('submit(companyInfo-save)',function (data){
                    request.post('/scm/company/update',data.field).then(res=>{
                        layer.close(fn.layer_index);
                        if(res.data==0){
                            layer.msg('资料修改成功');
                        }else if(res.data==1){
                            layer.confirm('您的公司资料已审核通过，请前往协议签约签署供应链服务协议。',{icon: 1},function (index) {
                                layer.close(index);
                                location.hash = '/company/agreement';
                            });
                        }else if(res.data==2){
                            layer.alert('您的公司资料已提交，我司会尽快审核您的公司信息。',{icon: 1});
                        }
                        if(fn.callBack){
                            eval(fn.callBack).call(this,data.field);
                        }
                    });
                });
            }
            ,async getCitys(cityName){
                let provinceName = $province.val();
                $city.get(0).length = 0;
                $area.get(0).length = 0;
                if(com.isNotEmpty(provinceName)){
                    let citys = await staticData.getCitys(provinceName);
                    com.fullSelect({
                        elem:$city,
                        data:citys,
                        label:'name',
                        value:'name',
                        defValue:cityName||'',
                        firstLabel:'请选择'
                    });
                }
                form.render('select','form-invoiceinfo-base-manage');
            }
            ,async getAreas(areaName){
                let provinceName = $province.val(),cityName = $city.val();
                $area.get(0).length = 0;
                if(com.isNotEmpty(provinceName)&&com.isNotEmpty(cityName)){
                    let areas = await staticData.getAreas(provinceName,cityName);
                    com.fullSelect({
                        elem:$area,
                        data:areas,
                        label:'name',
                        value:'name',
                        defValue:areaName||'',
                        firstLabel:'请选择'
                    });
                }
                form.render('select','form-invoiceinfo-base-manage');
            }
            // 修改开票信息
            ,async editInvoice(callBack){
                fn.callBack = callBack;
                await $.get('/views/sub/company-invoice-manage.html',{'v':setter.version},function (html) {
                    fn.layer_index = layer.open({
                        title: '开票信息维护'
                        , id: 'win-edit-invoice'
                        , type: 1
                        , resize: false
                        , shadeClose: true
                        , area: ['720px', 'auto']
                        , content: html
                    });
                });
                let companyData = await fn.getCompanyData();
                form.val('form-invoiceinfo-base-manage',companyData);
                let $formInvoiceInfo = $('#form-invoiceinfo-base-manage');
                $formInvoiceInfo.find('.upload-box').attr({'file-id': companyData.id, 'edit':'true','max-size':1});
                uploadList.init($formInvoiceInfo);
                $province = $('#company-invoice-manage-province');
                $city = $('#company-invoice-manage-city');
                $area = $('#company-invoice-manage-area');
                //获取省份信息
                let provinces = await staticData.getAllProvinces();
                com.fullSelect({
                    elem:$province,
                    data:provinces,
                    label:'name',
                    value:'name',
                    defValue:companyData.invoiceProvince || '',
                    firstLabel:'请选择'
                });
                await fn.getCitys(companyData.invoiceCity);
                await fn.getAreas(companyData.invoiceArea);
                form.render(null,'form-invoiceinfo-base-manage');
                form.on('submit(invoiceInfo-save)',function (data) {
                    request.post('/scm/company/updateInvoice',data.field).then(()=> {
                        layer.close(fn.layer_index);
                        layer.msg('资料修改成功');
                        if(fn.callBack){
                            eval(fn.callBack).call(this,data.field);
                        }
                    });
                });
            }
        };
    form.on('select(company-invoice-manage-province)',function () {
        fn.getCitys();
    });
    form.on('select(company-invoice-manage-city)',function () {
        fn.getAreas();
    });
    exports('companyInfo', fn)
})